<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Event Loops - Netty See</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <style>
        .eventloop-card {
            transition: transform 0.2s;
        }
        .eventloop-card:hover {
            transform: translateY(-2px);
        }
        .status-badge {
            font-size: 0.8rem;
        }
        .metric-small {
            font-size: 0.9rem;
        }
    </style>
</head>
<body>
    <nav class="navbar navbar-expand-lg navbar-dark bg-dark">
        <div class="container">
            <a class="navbar-brand" href="/">
                <i class="fas fa-network-wired"></i> Netty See
            </a>
            <div class="navbar-nav ms-auto">
                <a class="nav-link" href="/channels">Channels</a>
                <a class="nav-link active" href="/eventloops">Event Loops</a>
                <a class="nav-link" href="/performance">Performance</a>
                <a class="nav-link" href="/errors">错误分析</a>
            </div>
        </div>
    </nav>

    <div class="container mt-4">
        <div class="row">
            <div class="col-12">
                <div class="d-flex justify-content-between align-items-center mb-4">
                    <h1><i class="fas fa-sync-alt"></i> Event Loop 监控</h1>
                    <div>
                        <button class="btn btn-primary" onclick="refreshEventLoops()">
                            <i class="fas fa-sync-alt"></i> 刷新
                        </button>
                        <button class="btn btn-success" onclick="toggleAutoRefresh()">
                            <i class="fas fa-play" id="autoRefreshIcon"></i> 
                            <span id="autoRefreshText">开启自动刷新</span>
                        </button>
                    </div>
                </div>
            </div>
        </div>

        <!-- 统计概览 -->
        <div class="row mb-4">
            <div class="col-md-3">
                <div class="card bg-primary text-white">
                    <div class="card-body text-center">
                        <i class="fas fa-cogs fa-2x mb-2"></i>
                        <div class="h4" id="totalEventLoops">0</div>
                        <div>总 Event Loops</div>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="card bg-success text-white">
                    <div class="card-body text-center">
                        <i class="fas fa-play fa-2x mb-2"></i>
                        <div class="h4" id="activeEventLoops">0</div>
                        <div>活跃 Event Loops</div>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="card bg-info text-white">
                    <div class="card-body text-center">
                        <i class="fas fa-tasks fa-2x mb-2"></i>
                        <div class="h4" id="totalTasks">0</div>
                        <div>总任务数</div>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="card bg-warning text-white">
                    <div class="card-body text-center">
                        <i class="fas fa-clock fa-2x mb-2"></i>
                        <div class="h4" id="queuedTasks">0</div>
                        <div>队列任务</div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Event Loop 列表 -->
        <div class="row">
            <div class="col-12">
                <div class="card">
                    <div class="card-header">
                        <h5 class="mb-0">Event Loop 详情</h5>
                    </div>
                    <div class="card-body">
                        <div id="eventLoopContainer">
                            <div class="text-center text-muted">
                                <i class="fas fa-spinner fa-spin fa-2x"></i>
                                <div class="mt-2">加载中...</div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        let autoRefreshInterval;
        let isAutoRefresh = false;

        function refreshEventLoops() {
            fetch('/api/netty/eventloops')
                .then(response => {
                    if (!response.ok) {
                        throw new Error(`HTTP ${response.status}: ${response.statusText}`);
                    }
                    return response.json();
                })
                .then(data => {
                    updateEventLoopDisplay(data);
                    updateStatistics(data);
                })
                .catch(error => {
                    console.error('获取EventLoop数据失败:', error);
                    document.getElementById('eventLoopContainer').innerHTML = `
                        <div class="alert alert-danger">
                            <i class="fas fa-exclamation-triangle"></i>
                            获取EventLoop数据失败: ${error.message}
                        </div>
                    `;
                });
        }

        function updateEventLoopDisplay(eventLoops) {
            const container = document.getElementById('eventLoopContainer');
            
            if (!eventLoops || eventLoops.length === 0) {
                container.innerHTML = `
                    <div class="text-center text-muted">
                        <i class="fas fa-info-circle fa-2x"></i>
                        <div class="mt-2">暂无EventLoop数据</div>
                        <div class="mt-2">
                            <small>请确保有Netty应用正在运行并连接到监控服务器</small>
                        </div>
                    </div>
                `;
                return;
            }

            let html = '<div class="row">';
            
            eventLoops.forEach(eventLoop => {
                const statusClass = eventLoop.shutdown ? 'danger' : 'success';
                const statusText = eventLoop.shutdown ? '已关闭' : '运行中';
                const cpuUsage = (eventLoop.cpuUsage || 0).toFixed(1);
                
                html += `
                    <div class="col-md-6 col-lg-4 mb-3">
                        <div class="card eventloop-card h-100">
                            <div class="card-header d-flex justify-content-between align-items-center">
                                <h6 class="mb-0">${eventLoop.type || 'Unknown'}</h6>
                                <span class="badge bg-${statusClass} status-badge">${statusText}</span>
                            </div>
                            <div class="card-body">
                                <div class="row text-center">
                                    <div class="col-6">
                                        <div class="metric-small text-muted">线程数</div>
                                        <div class="h5">${eventLoop.threadCount || 1}</div>
                                    </div>
                                    <div class="col-6">
                                        <div class="metric-small text-muted">CPU使用率</div>
                                        <div class="h5">${cpuUsage}%</div>
                                    </div>
                                </div>
                                <hr>
                                <div class="row text-center">
                                    <div class="col-6">
                                        <div class="metric-small text-muted">已执行任务</div>
                                        <div class="h6">${eventLoop.tasksExecuted || 0}</div>
                                    </div>
                                    <div class="col-6">
                                        <div class="metric-small text-muted">队列任务</div>
                                        <div class="h6">${eventLoop.tasksQueued || 0}</div>
                                    </div>
                                </div>
                                ${eventLoop.channels && eventLoop.channels.length > 0 ? `
                                <hr>
                                <div class="metric-small text-muted mb-2">关联Channels (${eventLoop.channels.length})</div>
                                <div class="d-flex flex-wrap gap-1">
                                    ${eventLoop.channels.slice(0, 5).map(channelId => 
                                        `<a href="/channels?search=${channelId}" class="badge bg-secondary text-decoration-none" style="font-size: 0.7rem;" title="点击查看Channel详情">${channelId}</a>`
                                    ).join('')}
                                    ${eventLoop.channels.length > 5 ? 
                                        `<a href="/channels?eventloop=${encodeURIComponent(eventLoop.name || eventLoop.type)}" class="badge bg-info text-decoration-none" style="font-size: 0.7rem;" title="查看所有关联Channels">+${eventLoop.channels.length - 5}</a>` 
                                        : ''}
                                </div>
                                ` : ''}
                            </div>
                            <div class="card-footer d-flex justify-content-between align-items-center">
                                <small class="text-muted">
                                    <i class="fas fa-tag"></i> ${eventLoop.name || 'Unnamed EventLoop'}
                                </small>
                                ${eventLoop.channels && eventLoop.channels.length > 0 ? `
                                <a href="/channels?eventloop=${encodeURIComponent(eventLoop.name || eventLoop.type)}" 
                                   class="btn btn-sm btn-outline-primary" 
                                   title="查看所有关联的Channels">
                                    <i class="fas fa-external-link-alt"></i> 查看Channels
                                </a>
                                ` : ''}
                            </div>
                        </div>
                    </div>
                `;
            });
            
            html += '</div>';
            container.innerHTML = html;
        }

        function updateStatistics(eventLoops) {
            const total = eventLoops.length;
            const active = eventLoops.filter(el => !el.shutdown).length;
            const totalTasks = eventLoops.reduce((sum, el) => sum + (el.tasksExecuted || 0), 0);
            const queuedTasks = eventLoops.reduce((sum, el) => sum + (el.tasksQueued || 0), 0);

            document.getElementById('totalEventLoops').textContent = total;
            document.getElementById('activeEventLoops').textContent = active;
            document.getElementById('totalTasks').textContent = totalTasks;
            document.getElementById('queuedTasks').textContent = queuedTasks;
        }

        function toggleAutoRefresh() {
            if (isAutoRefresh) {
                clearInterval(autoRefreshInterval);
                isAutoRefresh = false;
                document.getElementById('autoRefreshIcon').className = 'fas fa-play';
                document.getElementById('autoRefreshText').textContent = '开启自动刷新';
            } else {
                autoRefreshInterval = setInterval(refreshEventLoops, 3000);
                isAutoRefresh = true;
                document.getElementById('autoRefreshIcon').className = 'fas fa-pause';
                document.getElementById('autoRefreshText').textContent = '关闭自动刷新';
            }
        }

        // 页面加载完成后初始化
        document.addEventListener('DOMContentLoaded', function() {
            refreshEventLoops();
        });
    </script>
</body>
</html>